<?php

/***********递归生成目录**********/
function mk_dir($path) {
	//第1种情况，该目录已经存在
	if (is_dir($path)) {
		return;
	}
	//第2种情况，父目录存在，本身不存在
	if (is_dir(dirname($path))) {
		mkdir($path, 0777);
	}
	//第3种情况，父目录不存在
	if (!is_dir(dirname($path))) {
		mk_dir(dirname($path)); //创建父目录
		mkdir($path, 0777);
	}
}

/********获取插图*******/
function getContentPic($conent) {
	preg_match_all('#<img.*?src="([^"]*)"[^>]*>#i', $conent, $match);
	if (!$match[1]) {
		return false;
	}

	foreach ($match[1] as $one) {
		$data[] = str_replace("<{ImgDomain}>", "", $one);
	}
	return $data;
}

/***
 *
 *
 *    //口语化时间
 *
 * */

function time_tran($the_time) {
	$now_time = time();
	$show_time = $the_time;
	$dur = $now_time - $show_time;
	switch ($dur) {
	case $dur < 0:
		return '1秒前';
		break;

	case $dur < 60:
		return $dur . '秒前';
		break;
	case $dur < 3600:
		return floor($dur / 60) . '分钟前';
		break;
	case strtotime(date("Y-m-d 00:00:00")) < $the_time && $the_time < strtotime(date("Y-m-d 23:59:00")):
		return "今天 " . date("H:i", $the_time);
		break;
	case $dur > 3600 * 24 && $dur < 3600 * 24 * 30: //30天前
		return floor($dur / (24 * 3600)) . '天前';
		break;
	case date("Y", $the_time) == date("Y", $now_time): //大于1天小于1年
		return date("m-d H:i", $the_time);
		break;
	default:
		return date("Y-m-d H:i", $the_time);
	}

}

/*******商家用户名*******/
function getStoreID() {
	$url = $_SERVER['HTTP_HOST'];
	$url = explode(".", $url);
	$store_domain = $url['0'];
	$data = BoxModel("system_store")->where("domain='$store_domain'")->find();
	//unset($_GET['storeDomain']);
	return $data['store_id'] ? $data['store_id'] : 1;

}

/**加密函数**/
function encrypt($value) {
	return md5($value);
}

/**获取ip**/
function getIp($type = 0) {
	$type = $type ? 1 : 0;
	static $ip = NULL;
	if ($ip !== NULL) {
		return $ip[$type];
	}

	if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
		$arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
		$pos = array_search('unknown', $arr);
		if (false !== $pos) {
			unset($arr[$pos]);
		}

		$ip = trim($arr[0]);
	} elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
		$ip = $_SERVER['HTTP_CLIENT_IP'];
	} elseif (isset($_SERVER['REMOTE_ADDR'])) {
		$ip = $_SERVER['REMOTE_ADDR'];
	}
	// IP地址合法验证
	$long = ip2long($ip);
	$ip = $long ? array($ip, $long) : array('0.0.0.0', 0);
	return $ip[$type];
}

/**组合一维数组 ├─ **/
function getTree($tree, $pid = 0, $level = 1) {
	if (!is_array($tree)) {
		return '';
	}

	static $data = array();
	foreach ($tree as $v) {
		if ($v['pid'] == $pid) {
			$level == 1 && $v['showname'] = $v['name'];
			$level == 2 && $v['showname'] = '&nbsp;&nbsp;├─' . $v['name'];
			$level >= 3 && $v['showname'] = str_repeat('&nbsp;&nbsp; ', $level - 2) . '&nbsp;&nbsp;&nbsp;&nbsp;├─' . $v['name'];
			$data[] = $v;
			getTree($tree, $v['id'], $level + 1);
		}
	}
	return $data;
}

/**
 * 组合多维数组
 */
function treeArr($cate, $pid = 0, $level = 0) {
	$arr = array();
	foreach ($cate as $v) {
		if ($v['parent_id'] == $pid) {
			$v['level'] = $level + 1;
			$v['child'] = treeArr($cate, $v['id'], $level + 1);
			$arr[] = $v;
		}
	}
	return $arr;
}

/*传递一个父级id返回所有子分类id*/

function getChildsId($cate, $pid) {
	$arr = array();
	foreach ($cate as $v) {
		if ($v['pid'] == $pid) {
			$arr[] = $v['id'];
			$arr = array_merge($arr, getChildsId($cate, $v['id']));
		}
	}
	return $arr;
}

/**
 * 判断url地址是否包含http://没有就加上
 */
function urlSet($myURL) {
	$myArray = explode("://", $myURL, 2);
	if ($myArray[0] == "http" || $myArray[0] == "https") {
		return $myURL;
	} else {
		return "http://" . $myURL;
	}
}

/**简化打印**/
function p($arr) {
	dump($arr, 1, '<pre>', 0);
}

/*****$url 为 相对与根目录，$param为数组参数***/
function thread($url, $param) {

	$md5name = md5(md5(C('runThreadKey')));
	$url = trim($url, "/");
	$url = "/" . $url . "/?md5name={$md5name}";
	foreach ($param as $key => $one) {
		$url .= "&{$key}={$one}";
	}
	$url .= "&k=1";
	$Host = rtrim(str_replace("http://", "", HomeUrl), "/");
	$fp = fsockopen($Host, 80, $errno, $errstr, 30);
	if (!$fp) {
		echo "$errstr ($errno)<br />\n";
	} else {
		$out = "GET {$url}/ HTTP/1.1\r\n";
		$out .= "Host: {$Host}\r\n";
		$out .= "Connection: Close\r\n\r\n";
		fwrite($fp, $out);
		/*忽略执行结果
			        while (!feof($fp)) {
			            echo fgets($fp, 128);
		*/
		fclose($fp);
	}
}

/**
 * 验证邮箱格式
 * @param  [type]  $email
 * @param  boolean $test_mx
 * @return boolean          [description]
 */
function is_email($email, $test_mx = false) {
	if (eregi("^([_a-z0-9-]+)(\.[_a-z0-9-]+)*@([a-z0-9-]+)(\.[a-z0-9-]+)*(\.[a-z]{1,4})$", $email)) {
		if ($test_mx) {
			list($username, $domain) = split("@", $email);
			return getmxrr($domain, $mxrecords);
		} else {
			return true;
		}
	} else {
		return false;
	}

}

/**
 * 查找字符串是否存在
 * @param  [type]  字符串
 * @param  [type]  要查找字符串
 * @return boolean
 */
function isInString($haystack, $needle) {
	return false !== strpos($haystack, $needle);
}

/**
 * 英文字符替换中文字符
 * @param  [type] $str
 * @return [type]      [description]
 */
function toChina($str) {
	$a = array(',', '?', '!');
	$b = array('，', '？', '！');
	return str_replace($a, $b, $str);
}

/**
 *
 * 是否手机访问
 *
 * 应用程序的控制器类可以覆盖该函数以使用自定义的成功提示
 *
 */
function mobile() {
	$user_agent = $_SERVER['HTTP_USER_AGENT'];
	$mobile_agents = Array("240x320", "acer", "acoon", "acs-", "abacho", "ahong", "airness", "alcatel", "amoi", "android", "anywhereyougo.com", "applewebkit/525", "applewebkit/532", "asus", "audio", "au-mic", "avantogo", "becker", "benq", "bilbo", "bird", "blackberry", "blazer", "bleu", "cdm-", "compal", "coolpad", "danger", "dbtel", "dopod", "elaine", "eric", "etouch", "fly ", "fly_", "fly-", "go.web", "goodaccess", "gradiente", "grundig", "haier", "hedy", "hitachi", "htc", "huawei", "hutchison", "inno", "ipad", "ipaq", "ipod", "jbrowser", "kddi", "kgt", "kwc", "lenovo", "lg ", "lg2", "lg3", "lg4", "lg5", "lg7", "lg8", "lg9", "lg-", "lge-", "lge9", "longcos", "maemo", "mercator", "meridian", "micromax", "midp", "mini", "mitsu", "mmm", "mmp", "mobi", "mot-", "moto", "nec-", "netfront", "newgen", "nexian", "nf-browser", "nintendo", "nitro", "nokia", "nook", "novarra", "obigo", "palm", "panasonic", "pantech", "philips", "phone", "pg-", "playstation", "pocket", "pt-", "qc-", "qtek", "rover", "sagem", "sama", "samu", "sanyo", "samsung", "sch-", "scooter", "sec-", "sendo", "sgh-", "sharp", "siemens", "sie-", "softbank", "sony", "spice", "sprint", "spv", "symbian", "tablet", "talkabout", "tcl-", "teleca", "telit", "tianyu", "tim-", "toshiba", "tsm", "up.browser", "utec", "utstar", "verykool", "virgin", "vk-", "voda", "voxtel", "vx", "wap", "wellco", "wig browser", "wii", "windows ce", "wireless", "xda", "xde", "zte");
	$is_mobile = false;
	foreach ($mobile_agents as $device) {
		if (stristr($user_agent, $device)) {
			$is_mobile = true;
			break;
		}
	}
	return $is_mobile;
	// return 1 ;
}

/****check微信浏览器****/
function checkAgent() {
	$useragent = addslashes($_SERVER['HTTP_USER_AGENT']);
	if (strpos($useragent, 'MicroMessenger') === false && strpos($useragent, 'Windows Phone') === false) {
		return true;
	} else {
		return false;
	}
}

/********订房日历******/
function calendar($date, $price_cs, $price, $book_data, $weekend_add_price) {
	$date = getdate(strtotime($date));
	$end = getdate(mktime(0, 0, 0, $date['mon'] + 1, 1, $date['year']) - 1);
	$start = getdate(mktime(0, 0, 0, $date['mon'], 1, $date['year']));
	$m = $date['year'] . "-" . ($date['mon'] < 10 ? "0" . $date['mon'] : $date['mon']); //当前年月份
	$next = date('Y-m-d', $end[0] + 86400);
	$arr_tpl = array(0 => '', 1 => '', 2 => '', 3 => '', 4 => '', 5 => '', 6 => '');
	$date_arr = array();
	$j = 0;
	for ($i = 0; $i < $end['mday']; $i++) {
		if (!isset($date_arr[$j])) {
			$date_arr[$j] = $arr_tpl;
		}
		$d = $date_arr[$j][($i + $start['wday']) % 7]['date'] = ($i + 1) < 10 ? "0" . ($i + 1) : ($i + 1); //当前日
		$now = $m . "-" . $d; //当前年月日
		$week = date("w", strtotime($now)); //周5 周六要补价
		$date_arr[$j][($i + $start['wday']) % 7]['now'] = strtotime($now); //当前日
		$date_arr[$j][($i + $start['wday']) % 7]['now_date'] = ($now); //当前日
		$date_arr[$j][($i + $start['wday']) % 7]['price'] = "￥" . $price;
		if ($week == 5 || $week == 6) {
			$date_arr[$j][($i + $start['wday']) % 7]['price'] = "￥" . ($price + $weekend_add_price); //周5 周六要补价
		}
		if ($price_cs[$now]) {
			$date_arr[$j][($i + $start['wday']) % 7]['price'] = "￥" . ($price_cs[$now]);
		}

		if ($book_data[$now] == '满房') {
			$date_arr[$j][($i + $start['wday']) % 7]['price'] = "满房";
		}
//当剩下房间为0时，就不可预定了
		if ($now < date("Y-m-d")) {
			$date_arr[$j][($i + $start['wday']) % 7]['price'] = "";
		}
//以前的不可预订0时，就不可预定了
		if ($date_arr[$j][6]) {
			$j++;
		}
	}
	//dump($date_arr);
	return array('data' => $date_arr, 'next' => $next);
}

/**
 * 生成订单号
 */
function createOrderNo() {
	$year_code = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
	return $year_code[intval(date('Y')) - 2010] .
	strtoupper(dechex(date('m'))) . date('d') .
	substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('d', rand(0, 99));
}

/**
 * 生成随机数
 */

function great_rand($len = 8, $format = 'ALL') {
	$is_abc = $is_numer = 0;
	$password = $tmp = '';
	switch ($format) {
	case 'ALL':
		$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
		break;
	case 'CHAR':
		$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
		break;
	case 'NUMBER':
		$chars = '0123456789';
		break;
	default:
		$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
		break;
	} // www.jb51.net
	mt_srand((double) microtime() * 1000000 * getmypid());
	while (strlen($password) < $len) {
		$tmp = substr($chars, (mt_rand() % strlen($chars)), 1);
		if (($is_numer != 1 && is_numeric($tmp) && $tmp > 0) || $format == 'CHAR') {
			$is_numer = 1;
		}
		if (($is_abc != 1 && preg_match('/[a-zA-Z]/', $tmp)) || $format == 'NUMBER') {
			$is_abc = 1;
		}
		$password .= $tmp;
	}
	if ($is_numer != 1 || $is_abc != 1 || empty($password)) {
		$password = randpw($len, $format);
	}
	return $password;
}

/**
 * 生成订单号
 */
function createCardNo($i) {
	$ym = date('ym');
	$batch = strtoupper(great_rand(10));
	$sn = sprintf("%02s%s%06s", $batch, $ym, $i);
	return $sn;
}

/***微信中发送文本***/
function wx_text($user_id, $content) {
	$userInfo = BoxModel("SystemMember")->load($user_id);
	$storeInfo = BoxModel("SystemStore")->load($userInfo['store_id']);
	if (!$userInfo['openid']) {
		return;
	}
	$param = array(
		'token' => $storeInfo['token'],
		'appID' => $storeInfo['appID'],
		'appsecret' => $storeInfo['appsecret'],
	);
	$wechatObj = new \Common\Org\weiXin($param);
	$r = $wechatObj->sendText($userInfo['openid'], $content);
	return $r;
}

/****发微信服务提 醒*/
function wx_msg($title, $user_id, $topic, $info, $url) {
	$userInfo = BoxModel("SystemMember")->where(array('user_id' => $user_id))->find();
	$storeInfo = BoxModel("addon_wx_config")->where(array('store_id' => $userInfo['store_id']))->find();
	if (!$userInfo['openid']) {
		return array('msg' => $user_id . '用户信息不存在openid');
	}
	$param = array(
		'token' => $storeInfo['token'],
		'appID' => $storeInfo['appID'],
		'appsecret' => $storeInfo['appsecret'],
	);
	$wechatObj = new \Common\Org\weiXin($param);
	$data = array(
		'first' => $title,
		'keyword1' => $topic,
		'keyword2' => date("Y-m-d H:i:s"),
		'remark' => $info,
		'url' => $url,
	);
	$r = $wechatObj->templateSend($userInfo['openid'], $data, "9Ad5pMlpnGlaHSbwwmkiMQX1sp4zA0Ny36ofDAWuR2g");
	return $r;
}

function cutstr($str, $length = 0, $append = true, $charset = 'utf8') {
	$str = trim($str);
	$strlength = strlen($str);
	$charset = strtolower($charset);
	if ($charset == 'utf8') {
		$l = 0;
		while ($i <= $strlength) {
			if (ord($str{
				$i}) < 0x80
			) {
				$l++;
				$i++;
			} else
			if (ord($str{
				$i}) < 0xe0
			) {
				$l++;
				$i += 2;
			} else
			if (ord($str{
				$i}) < 0xf0
			) {
				$l += 2;
				$i += 3;
			} else
			if (ord($str{
				$i}) < 0xf8
			) {
				$l += 1;
				$i += 4;
			} else
			if (ord($str{
				$i}) < 0xfc
			) {
				$l += 1;
				$i += 5;
			} else
			if (ord($str{
				$i}) < 0xfe
			) {
				$l += 1;
				$i += 6;
			}

			if ($l >= $length) {
				$newstr = substr($str, 0, $i);
				break;
			}
		}
		if ($l < $length) {
			return $str;
		}
	} elseif ($charset == 'gbk') {
		if ($length == 0 || $length >= $strlength) {
			return $str;
		}
		while ($i <= $strlength) {
			if (ord($str{
				$i}) > 0xa0
			) {
				$l += 2;
				$i += 2;
			} else {
				$l++;
				$i++;
			}

			if ($l >= $length) {
				$newstr = substr($str, 0, $i);
				break;
			}
		}
	}

	if ($append && $str != $newstr) {
		$newstr .= '...';
	}

	return $newstr;
}
//记日志
function Logs($type, $info) {
	$row = array(
		'type' => $type,
		'msg' => serialize($info),
		'ip' => getIp(),
		'add_time' => date("Y-m-d H:i:s"),
	);
	BoxModel("system_error_logs")->add($row);
}

/**
 *  调用事务，$name 为项目，（ Mall,SNS） Class 为文件名
 */
function Logic($name, $class) {
	$class = ucfirst($class);
	$name = ucfirst($name);
	$classname = $name . "\\Logic\\" . $class . "Logic";
	if ($GLOBALS['Logic'][$classname]) {
		return $GLOBALS['Logic'][$classname];
	}
	$file = BOX_PATH . "/Apps/" . $name . "/Logic/" . $class . "Logic.class.php";
	if (file_exists($file)) {
		include_once $file;
		if (class_exists($classname)) {
			$obj = new $classname();
			$GLOBALS['Logic'][$classname] = $obj;
			return $obj;
		} else {
			throw new \Exception(L('_Widget_Class_NOT_EXIST_') . $file);
		}
	} else {
		return false;
	}

}

/**
 *  调用小组件，$name 为项目，（ Mall,SNS） Class 为文件名
 */
function Widget($name, $params) {
	$p = explode("/", $name);
	$name = $p['0'];
	$class = $p['1'];
	$tpl_name = $act = $p['2'];
	if ($p[3] == 'tpl') {
		$tpl_name = $p['4'];
	}
	$classname = $name . "\\Widget\\" . $class . "Widget";
	if ($GLOBALS['Widget'][$classname]) {
		$obj = $GLOBALS['Widget'][$classname];
	} else {
		$file = BOX_PATH . "/Apps/" . $name . "/Widget/" . $class . "Widget.class.php";
		if (file_exists($file)) {
			include_once $file;
			if (class_exists($classname)) {
				$obj = new $classname();
				$GLOBALS['Widget'][$classname] = $obj;
			} else {
				throw new \Exception(L('_Widget_Class_NOT_EXIST_') . $file);
			}
		} else {
			throw new \Exception(L('_Widget_File_NOT_EXIST_') . $file);
		}
	}
	$obj->WidgetViewUrl = BOX_PATH . "/Apps/" . $name . "/Widget/View/" . $class . "/" . $tpl_name . ".html";
	if ($act) {
		return $obj->$act($params);
	} else {
		return $obj;
	}

}

/******分页****/
function setPager($count, $limit) {
	$Page = new \Common\Org\Page($count, $limit); // 实例化分页类
	$Page->setConfig('prev', '上一页');
	$Page->setConfig('next', '下一页');
	$Page->setConfig('first', '首页');
	$Page->setConfig('last', '末页');
	$Page->setConfig('theme', '%totalRow% %first% %upPage% %linkPage%  %downPage% %end%');
	//$this->page  = $Page->show();// 分页显示输出
	$Page->limit = $Page->firstRow . ',' . $Page->listRows;
	$Page->show = $Page->show(); // 分页显示输出
	//dump($Page);
	$data = array(
		'rollPage' => $Page->rollPage,
		'parameter' => $Page->parameter,
		'url' => $Page->url,
		'listRows' => $Page->listRows,
		'firstRow' => $Page->firstRow,
		'totalPages' => $Page->totalPages,
		'nowPage' => $Page->nowPage,
		'coolPages' => $Page->coolPages,
		'show' => $Page->show,
		'limit' => $Page->limit,
	);
	return $data;

}

/**
 * 新浪生成短连接接口
 * @param  string $url 长连接
 * @param  string $source key
 * @return string  短链接
 */
function shortUrl($url, $source = '43553952') {
	$url = urlencode($url);
	$get_url = "https://api.weibo.com/2/short_url/shorten.json?source=$source&url_long=$url";
	$get = json_decode(file_get_contents($get_url), true);
	return $get['urls'][0]['url_short'] ? $get['urls'][0]['url_short'] : '#';
}

/**
 * 生成会员编号
 * @param  integer $store_id 商店id
 * @return string
 */
function cnumber($number = 0, $len = 2) {
	$len = $len - strlen($number);
	if ($len > 0) {
		$number .= str_repeat('0', $len - 1) . $number;
	}
	return $number;
}

/**
 * 字典
 * @param  integer dict
 * @return string
 */
function dict($name = "", $value = "", $remark = "") {
	if ($value === true) {
		$data = BoxModel("SystemDict")->load($name);
		return json_decode(json_encode($data));
	} else {
		$data = BoxModel("SystemDict")->load($name, $value, $remark);
		return $data;
	}

}

/*******数组转字符***/
function arrayeval($array, $level = 0) {

	$space = '';

	for ($i = 0; $i <= $level; $i++) {

		$space .= "\t";

	}

	$evaluate = "Array\n$space(\n";

	$comma = $space;

	foreach ($array as $key => $val) {

		$key = is_string($key) ? '\'' . addcslashes($key, '\'\\') . '\'' : $key;

		$val = !is_array($val) && (!preg_match("/^\-?\d+$/", $val) || strlen($val) > 12) ? '\'' . addcslashes($val, '\'\\') . '\'' : $val;

		if (is_array($val)) {

			$evaluate .= "$comma$key => " . arrayeval($val, $level + 1);

		} else {

			$evaluate .= "$comma$key => $val";

		}

		$comma = ",\n$space";

	}

	$evaluate .= "\n$space)";

	return $evaluate;

}

/**
 * cutl
 * @param  array post_file
 * @param  string url
 * @return string
 */
function mycurl($url, $post_file, $file = 0, $write) {

	if ($file) {
		$cookie_dir = BOX_PATH . "/Runtime/cookie";
		$SCRIPT_ROOT = $cookie_dir . "/" . $file;

		if (!is_dir($cookie_dir)) {
			mk_dir($cookie_dir);
		}
		$_GET['SCRIPT_ROOT'] = $SCRIPT_ROOT;
		if (is_readable($SCRIPT_ROOT) == false) {
			$fp = fopen("$SCRIPT_ROOT", "a+");
			//$content=file_get_contents($cookie_dir."/360E19.tmp");
			//	file_put_contents("$SCRIPT_ROOT",$content);
			fclose($fp);
			$bool = tempnam($SCRIPT_ROOT, 'JSESSIONID');
			//	dump($bool);exit();
		}
		$cookie_file = $SCRIPT_ROOT;

	}

	$agent = 'Mozilla/5.0 (Windows NT 6.3; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0';

	$ch = curl_init(); /////初始化一个CURL对象
	curl_setopt($ch, CURLOPT_URL, $url);
	//curl_setopt($ch, CURLOPT_HTTPHEADER,$headerArr);  //构造IP
	//curl_setopt($ch, CURLOPT_HEADER, 1);
	//$headers = array();
	$headers = "'User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0"; ////定义content-type为plain

	//curl 'http://kjks.bjcz.gov.cn/cjcx/page/cjcx.pr.prcjcxdl_CJQuery.do' -H 'User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0' --data 'KJ_KSCJXX%2FPNAME=%CE%C2%D7%F7%C8%A8&KJ_KSCJXX%2FCID=441424198908176578&KJ_KSPHONE%2FPHONENM=15502154827'
	//$header[] = "User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0";
	// $header=implode(";",$header);
	curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); //设置HTTP头
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); ///设置不输出在浏览器上
	curl_setopt($ch, CURLOPT_TIMEOUT, 30); //50秒超时
	curl_setopt($ch, CURLOPT_USERAGENT, $agent);

	/*curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_BASIC); //代理认证模式
		    curl_setopt($ch, CURLOPT_PROXY, "58.220.2.133"); //代理服务器地址
		    curl_setopt($ch, CURLOPT_PROXYPORT, 80); //代理服务器端口
		    //curl_setopt($ch, CURLOPT_PROXYUSERPWD, ":"); //http代理认证帐号，username:password的格式
	*/

	/******提交********/
	if ($post_file) {
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $post_file); ////传递一个作为HTTP "POST"操作的所有数据的字符
	}

	if ($file) {
		if ($write) {
			curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file); //保存
		} else {
			curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
		}
	}

	//		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
	/***认证**/
	//curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,true); ;
	// curl_setopt($ch,CURLOPT_CAINFO,ROOT_PATH.'/cacert.pem');
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
	$content = curl_exec($ch);
	//dump($ch);
	if (curl_errno($ch)) {
//出错则显示错误信息
		return array('error' => 1, 'content' => curl_error($ch));
	}
	return $content;
}

/**
 * 通过百度地图API， 用ip定位
 * @param  integer dict
 * @return string
 */
function location($ip) {
	$url = "http://api.map.baidu.com/location/ip?ak=IUo2IPeICn2i2h6y2vWG6K0T&ip={$ip}&coor=bd09ll";
	$data = json_decode(mycurl($url), true);
	return $data;
}

/**
 * 通过百度地图API， 坐标转换为百度坐标
 */
function geoconv($point) {
	$url = "http://api.map.baidu.com/geoconv/v1/?ak=IUo2IPeICn2i2h6y2vWG6K0T&coords={$point}";
	$data = json_decode(mycurl($url), true);
	return $data;
}

//金山词霸开放平台API
//API key：2EAB7B39653B2440C7A53B2FE19F4C52
function eng_dictionary($word) {
	$data = S("eng_" . $word);
	if ($data) {
		return $data;
	}
	$url = "http://dict-co.iciba.com/api/dictionary.php?w=" . $word . "&key=2EAB7B39653B2440C7A53B2FE19F4C52&type=json";
	$content = mycurl($url);
	//dump($content);
	$data = json_decode($content, true);
	if (is_array($data)) {
		S("eng_" . $word, $data);
	}
	return $data;
}

/**
 * 7      * 保存文件
 * 8      *
 * 9      * @param string $fileName 文件名（含相对路径）
 * 10      * @param string $text 文件内容
 * 11      * @return boolean
 * 12      */
function saveFile($fileName, $text) {
	if (!$fileName || !$text) {
		return false;
	}

	if ($fp = fopen($fileName, "w")) {
		if (@fwrite($fp, $text)) {
			fclose($fp);
			return true;
		} else {
			fclose($fp);
			return false;
		}
	}
	return false;
}

/******查找一个目录下的所有文件******/
function getFile($dir) {
	if (is_file($dir)) {
		return array($dir);
	}
	$files = array();
	if (is_dir($dir) && ($dir_p = opendir($dir))) {
		$ds = DIRECTORY_SEPARATOR;
		while (($filename = readdir($dir_p)) !== false) {
			if ($filename == '.' || $filename == '..') {
				continue;
			}
			$filetype = filetype($dir . $ds . $filename);
			if ($filetype == 'dir') {
				$files = array_merge($files, getFile($dir . $ds . $filename));
			} elseif ($filetype == 'file') {
				$files[] = $dir . $ds . $filename;
			}
		}
		closedir($dir_p);
	}
	return $files;
}

/*************汉字的首写字母************/
function getfirstchar($s0) {
	$fchar = ord($s0{0});
	if ($fchar >= ord("A") and $fchar <= ord("z")) {
		return strtoupper($s0{0});
	}

	$s1 = iconv("UTF-8", "gb2312", $s0);
	$s2 = iconv("gb2312", "UTF-8", $s1);
	if ($s2 == $s0) {
		$s = $s1;
	} else {
		$s = $s0;
	}
	$asc = ord($s{0}) * 256 + ord($s{1}) - 65536;
	if ($asc >= -20319 and $asc <= -20284) {
		return "A";
	}

	if ($asc >= -20283 and $asc <= -19776) {
		return "B";
	}

	if ($asc >= -19775 and $asc <= -19219) {
		return "C";
	}

	if ($asc >= -19218 and $asc <= -18711) {
		return "D";
	}

	if ($asc >= -18710 and $asc <= -18527) {
		return "E";
	}

	if ($asc >= -18526 and $asc <= -18240) {
		return "F";
	}

	if ($asc >= -18239 and $asc <= -17923) {
		return "G";
	}

	if ($asc >= -17922 and $asc <= -17418) {
		return "I";
	}

	if ($asc >= -17417 and $asc <= -16475) {
		return "J";
	}

	if ($asc >= -16474 and $asc <= -16213) {
		return "K";
	}

	if ($asc >= -16212 and $asc <= -15641) {
		return "L";
	}

	if ($asc >= -15640 and $asc <= -15166) {
		return "M";
	}

	if ($asc >= -15165 and $asc <= -14923) {
		return "N";
	}

	if ($asc >= -14922 and $asc <= -14915) {
		return "O";
	}

	if ($asc >= -14914 and $asc <= -14631) {
		return "P";
	}

	if ($asc >= -14630 and $asc <= -14150) {
		return "Q";
	}

	if ($asc >= -14149 and $asc <= -14091) {
		return "R";
	}

	if ($asc >= -14090 and $asc <= -13319) {
		return "S";
	}

	if ($asc >= -13318 and $asc <= -12839) {
		return "T";
	}

	if ($asc >= -12838 and $asc <= -12557) {
		return "W";
	}

	if ($asc >= -12556 and $asc <= -11848) {
		return "X";
	}

	if ($asc >= -11847 and $asc <= -11056) {
		return "Y";
	}

	if ($asc >= -11055 and $asc <= -10247) {
		return "Z";
	}

	return null;
}

/*****发短信***/
function sms($tel, $msg) {
	$driver = C("smsDriver");
	$sms = new \Common\Org\Sms\Sms($driver);
	$result = $sms->send($tel, $msg);
	return $result;
}

/**
 * @desc 根据两点间的经纬度计算距离
 * @param float $lat 纬度值
 * @param float $lng 经度值
 */
function getDistance($lng1, $lat1, $lng2, $lat2) {
	$earthRadius = 6367000; //approximate radius of earth in meters

	/*
		      Convert these degrees to radians
		      to work with the formula
	*/
	$lat1 = ($lat1 * pi()) / 180;
	$lng1 = ($lng1 * pi()) / 180;

	$lat2 = ($lat2 * pi()) / 180;
	$lng2 = ($lng2 * pi()) / 180;
	/*
		      Using the
		      Haversine formula
		      http://en.wikipedia.org/wiki/Haversine_formula

		      calculate the distance
	*/

	$calcLongitude = $lng2 - $lng1;
	$calcLatitude = $lat2 - $lat1;
	$stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
	$stepTwo = 2 * asin(min(1, sqrt($stepOne)));
	$calculatedDistance = $earthRadius * $stepTwo;
	return round($calculatedDistance);
}

/******获得mysql返回sql***/
function getDistanceSql($lng2, $lat2) {
	$getDistanceSql = "";
	$earthRadius = 6367000; //approximate radius of earth in meters
	/*
	      Convert these degrees to radians
	      to work with the formula
*/
	$lat1 = "(lat * " . pi() . " ) / 180";
	$lng1 = "(lng * " . pi() . " ) / 180";

	$lat2 = "($lat2 * " . pi() . " ) / 180";
	$lng2 = "($lng2 * " . pi() . " ) / 180";
	/*
		      Using the
		      Haversine formula
		      http://en.wikipedia.org/wiki/Haversine_formula

		      calculate the distance
	*/
	$calcLongitude = "($lng2- $lng1)";
	$calcLatitude = "($lat2-$lat1)";
	$stepOne = "pow(sin(" . $calcLatitude . " / 2), 2) + cos(" . $lat1 . ") * cos(" . $lat2 . ") * pow(sin(" . $calcLongitude . " / 2), 2)";
	$stepTwo = "2 * asin(min( sqrt(" . $stepOne . ")))";
	$calculatedDistance = $earthRadius . " * " . $stepTwo;
	return $calculatedDistance;
}

/*******@的名字变成链接*****/
function AtStr($content) {
	preg_match_all('~\@([\w\d\_\-\x7f-\xff]+)(?:[\r\n\t\s ]+|[\xa1\xa1]+|[\xa3\xac]|[\xef\xbc\x8c]|[\,\.\;\[\#])~', $content, $match);
	$member = BoxModel("SystemMember");
	foreach ($match[1] as $one) {
		$r = $member->ByField('screen_name', $one);
		$user_ids[] = $r['user_id'];
	}
	foreach ($match[0] as $key => $one) {
		if ($user_ids[$key]) {
			$url = '<a style="color:blue" href="' . HomeUrl . 'u/' . $user_ids[$key] . '/' . '">' . $one . '</a>';
			$content = str_replace($one, $url, $content);
		}
	}
	return $content;

}

/********url转超连接********/
function autolink($foo) {
	// Modified from:  http://www.szcpost.com
	$foo = eregi_replace('(((f|ht){1}tp://)[-a-zA-Z0-9@:%_\+.~#?&//=]+)', '<a href="\\1" target="_blank" rel="nofollow">\\1</a>', $foo);
	if (strpos($foo, "http") === FALSE) {
		$foo = eregi_replace('(www.[-a-zA-Z0-9@:%_\+.~#?&//=]+)', '<a href="http://\\1" target="_blank" rel="nofollow" >\\1</a>', $foo);
	} else {
		$foo = eregi_replace('([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_\+.~#?&//=]+)', '\\1<a href="http://\\2" target="_blank" rel="nofollow" >\\2</a>', $foo);
	}
	return $foo;
}

/****变量使用双峰*****/
function convertUnderline2($str, $ucfirst = true) {
	$str = explode('_', $str);
	foreach ($str as $key => $val) {
		$str[$key] = ucfirst($val);
	}

	if (!$ucfirst) {
		$str[0] = strtolower($str[0]);
	}

	return implode('', $str);
}

function getModelPath($name) {
	$d = COMMON_PATH . "Model/" . $name . "Model.class.php"; //exit();
	$apps = getApps();
	if (is_file($d)) {
		return "common";
	}
	foreach ($apps as $one) {
		$f = APP_PATH . $one . "/Model/" . $name . "Model.class.php";
		if (is_file($f)) {
			return $one;
			break;
		}
	}

	$addons = getAddons();
	foreach ($addons as $one) {
		$f = ADDONS_PATH . $one . "/Model/" . $name . "Model.class.php";
		if (is_file($f)) {
			return array('Addons', $one, $name);
			break;
		}
	}

	if (strpos($name, "://") > -1) {
		$p = explode("://", $name);
		$ret[] = $p[0];
		if ($p[1]) {
			$p2 = explode("/", $p[1]);
		}
		$ret = array_merge($ret, (array) $p2);
		return $ret;
	}
	return "";
}

/******的box实例model方法 D方法扩展*******/
function BoxModel($name, $layer = "") {
	$name = convertUnderline2($name);
	static $_model = array();
	$layer = $layer ?: C('DEFAULT_M_LAYER');
	if (isset($_model[$name . $layer])) {
		return $_model[$name . $layer];
	}
	$dns = C('DB_DSNS');
	//$connection = C('DB_DSN'); //默认数据库连接
	/*****根据表前缀找数据库连接****/
	foreach ($dns as $k => $one) {
		//dump(strtolower($name));
		if (strpos(strtolower($name), $k) === 0) {
			$connection = $one;
			break;
		}
	}
	//在项目中找model
	$path_name = getModelPath($name);
	if ($path_name) {
		if ($path_name == "common") {
			$class = '\\Common\\' . $layer . '\\' . $name . $layer;
		} elseif (is_array($path_name)) {
			$class = '\\' . $path_name[0] . '\\' . ucfirst($path_name[1]) . '\\' . $layer . '\\' . $path_name[2] . $layer;
			$name = $path_name[2];
		} else {
			$class = '\\Apps\\' . ucfirst($path_name) . '\\' . $layer . '\\' . $name . $layer;
		}

		//dump($name);
		$model = new $class($name, "", $connection);
	} else {
		$model = new BaseModel(basename($name), "", $connection);
	}
	$_model[$name . $layer] = $model;
	return $model;
}

function startwith($str, $pattern) {
	if (strpos($str, $pattern) === 0) {
		return true;
	} else {
		return false;
	}

}

/*******获app项目****/
function getApps() {
	$apps = scandir(APP_PATH);
	foreach ($apps as $app) {
		$app = trim($app, ".");
		if ($app) {
			$new_apps[] = $app;
		}

	}
	return $new_apps;
}

/*******获所有插件目录****/
function getAddons() {
	$apps = scandir(ADDONS_PATH);
	foreach ($apps as $app) {
		$app = trim($app, ".");
		if ($app) {
			$new_apps[] = $app;
		}

	}
	return $new_apps;
}

/**
 * 处理插件钩子
 * @param string $hook 钩子名称
 * @param mixed $params 传入参数
 * @return void
 */
function hook($hook, &$params) {
	//$params=(array)$params;
	$list = explode("/", $hook);
	$file = ADDONS_PATH . "/$list[0]/Controller/$list[1]Controller.class.php";
	if (is_file($file)) {
//插件
		//dump($hook);
		$tag = "Addons\\$list[0]\\Controller\\$list[1]Controller";
		if (!class_exists($tag)) {
			throw new \Exception($file . L('_CLASS_NOT_EXIST_') . $tag);
		}
		$class = new $tag();
		$class->ViewPath = array(
			'name' => $list['0'],
			'controller' => $list['1'],
			'act' => $list['2'],
		);
		$r = $class->$list[2]($params);
		return $r;
	} elseif (strpos($hook, "/") > -1) {
		throw new \Exception($file . L('_methodes_NOT_EXIST_') . $list[1]);
	} else {
//勾子
		run_hook_func($hook, $params);
	}

}

/**
 * 勾子函数
 * @param strng $name
 */
function run_hook_func($hook_name, &$param) {
	//dump($hook_name);
	$hooks_data = BoxModel("SystemHooks")->get_hooks($hook_name);
	//dump($hooks_data);
	if ($hooks_data['status'] == 2) {
		return false;
	}
	$hook_list = get_hook_list();
	//dump($hook_name);
	foreach ($hook_list as $hook) {
		//dump( $hook);
		$class = new \ReflectionClass($hook);
		$obj = new $hook();
		if (is_array($hooks_data)) {
			foreach ($hooks_data as $hook_act) {
				if ($class->hasMethod($hook_act)) {
					$obj->$hook_act($param);
				}
			}
		} else {
			if ($class->hasMethod($hook_name)) {
				$obj->$hook_name($param);
			}
		}
	}
}

/***获得所有项目下的勾子文件****/
function get_hook_list() {
	$apps = getApps();
	$hook_list = array();
	foreach ($apps as $app) {
		$l = scandir(APP_PATH . "/" . $app . "/Hooks/");
		if ($l) {
			$hook_list[$app] = $l;
		}
	}
	$hook_list_class = array();
	foreach ($hook_list as $k => $data) {
		foreach ($data as $one) {
			$file = APP_PATH . $k . "/Hooks/" . $one;
			if (is_file($file)) {
				$name = basename($file);
				$class = "\\" . $k . "\\Hooks\\" . str_replace(".class.php", "", $name);
				if (class_exists($class)) {
					$hook_list_class[] = $class;
				}
			}
		}
	}
	return $hook_list_class;
}

/******导入一个目录的所有文件**/
function import_path($path) {
	$list = scandir($path);
	foreach ($list as $k => $one) {
		$file = $path . $one;
		$name = basename($file);
		include_once $file;
	}
}

/**
 * 获取插件类的类名
 * @param strng $name 插件名
 */
function get_addon_class($name) {
	$class = "Addons\\{$name}\\{$name}Addon";
	return $class;
}

/**
 * 获取插件类的类名
 * @param strng $name 实例化
 */
function addon_class($name) {
	$name = get_addon_class($name);
	static $_addon = array();
	if (isset($_addon[$name])) {
		return $_addon[$name];
	}
	$class = new $name();
	$_addon[$name] = $class;
	return $class;
}

/**
 * 获取插件类的配置文件数组
 * @param string $name 插件名
 */
function get_addon_config($name) {
	$class = get_addon_class($name);
	if (class_exists($class)) {
		$addon = new $class();
		return $addon->getConfig();
	} else {
		return array();
	}
}

/**
 * 插件显示内容里生成访问插件的url
 * @param string $url url
 * @param array $param 参数
 */
function addons_url($url, $param = array(), $suffix = true, $domain = false) {
	//dump(ADDON_NAME);
	//dump(ADDON_CLASS);
	//dump(ADDON_METHOD);
	$info = parse_url($url);
	$url = $info['path'];
	// dump($info);
	if ($url) {
		$p = explode("/", $url);
		if (count($p) == 1) {
			$url = "BoxAddon/" . ADDON_NAME . "/" . ADDON_CLASS . "/" . $url;
		}
		if (count($p) == 2) {
			$url = "BoxAddon/" . ADDON_NAME . "/" . $url;
		}
		if (count($p) == 3) {
			$url = "BoxAddon/" . $url;
		}
	} else {
		$url = "BoxAddon/" . ADDON_NAME . "/" . ADDON_CLASS . "/" . ADDON_METHOD;
	}

	$url = U($url, $param, $suffix, $domain);
	return $url;

}

/**
 * BoxApi内容里生成访问插件的url
 * @param string $url url
 * @param array $param 参数
 */
function api_url($url, $param = array(), $suffix = true, $domain = false) {
	$url = U($url, $param, $suffix, $domain);
	$url = "/BoxApi" . $url;
	return $url;

}

/**
 * get_some_day  获取n天前0点的时间戳
 * @param int $some n天
 * @param null $day 当前时间
 * @return int|null
 * @author:xjw129xjt(肖骏涛) xjt@ourstu.com
 */
function get_some_day($some = 30, $day = null) {
	$time = $day ? $day : time();
	$some_day = $time - 60 * 60 * 24 * $some;
	$btime = date('Y-m-d' . ' 00:00:00', $some_day);
	$some_day = strtotime($btime);
	return $some_day;
}

/*
 *
 *second_change秒转换为时分秒
 */
function second_change($sec) {
	$round = round($sec);
	return gmstrftime('%H:%M:%S', $round);
}

/**
 * 系统加密方法
 * @param string $data 要加密的字符串
 * @param string $key 加密密钥
 * @param int $expire 过期时间 单位 秒
 * @return string
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function thinkEncrypt($data, $key = '', $expire = 0) {
	$key = md5(empty($key) ? C('thinkEncryptKey') : $key);
	$data = base64_encode(serialize($data));
	$x = 0;
	$len = strlen($data);
	$l = strlen($key);
	$char = '';

	for ($i = 0; $i < $len; $i++) {
		if ($x == $l) {
			$x = 0;
		}

		$char .= substr($key, $x, 1);
		$x++;
	}

	$str = sprintf('%010d', $expire ? $expire + time() : 0);

	for ($i = 0; $i < $len; $i++) {
		$str .= chr(ord(substr($data, $i, 1)) + (ord(substr($char, $i, 1))) % 256);
	}
	return str_replace(array('+', '/', '='), array('-', '_', ''), base64_encode($str));
}

/**
 * 系统解密方法
 * @param  string $data 要解密的字符串 （必须是think_encrypt方法加密的字符串）
 * @param  string $key 加密密钥
 * @return string
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function thinkDecrypt($data, $key = '') {
	$key = md5(empty($key) ? C('thinkEncryptKey') : $key);
	$data = str_replace(array('-', '_'), array('+', '/'), $data);
	$mod4 = strlen($data) % 4;
	if ($mod4) {
		$data .= substr('====', $mod4);
	}
	$data = base64_decode($data);
	$expire = substr($data, 0, 10);
	$data = substr($data, 10);

	if ($expire > 0 && $expire < time()) {
		return '';
	}
	$x = 0;
	$len = strlen($data);
	$l = strlen($key);
	$char = $str = '';

	for ($i = 0; $i < $len; $i++) {
		if ($x == $l) {
			$x = 0;
		}

		$char .= substr($key, $x, 1);
		$x++;
	}

	for ($i = 0; $i < $len; $i++) {
		if (ord(substr($data, $i, 1)) < ord(substr($char, $i, 1))) {
			$str .= chr((ord(substr($data, $i, 1)) + 256) - ord(substr($char, $i, 1)));
		} else {
			$str .= chr(ord(substr($data, $i, 1)) - ord(substr($char, $i, 1)));
		}
	}
	return unserialize(base64_decode($str));
}

/**
 * 数据签名认证
 * @param  array $data 被认证的数据
 * @return string       签名
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function dataAuthSign($data) {
	//数据类型检测
	if (!is_array($data)) {
		$data = (array) $data;
	}
	ksort($data); //排序
	$code = http_build_query($data); //url编码并生成query字符串
	$sign = sha1($code); //生成签名
	return $sign;
}

/******是否手机号**/
function is_tel($mobile) {
	if (!is_numeric($mobile)) {
		return false;
	}
	return preg_match('#^^1[\d]{10}$#', $mobile) ? true : false;
}

/********数字转中文***/
function number2Chinese($num, $m = 1) {
	switch ($m) {
	case 0:
		$CNum = array(
			array('零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'),
			array('', '拾', '佰', '仟'),
			array('', '萬', '億', '萬億'),
		);
		break;
	default:
		$CNum = array(
			array('零', '一', '二', '三', '四', '五', '六', '七', '八', '九'),
			array('', '十', '百', '千'),
			array('', '万', '亿', '万亿'),
		);
		break;
	}
// $cNum = array('零','一','二','三','四','五','六','七','八','九');

	if (is_integer($num)) {
		$int = (string) $num;
	} else if (is_numeric($num)) {
		$num = explode('.', (string) floatval($num));
		$int = $num[0];
		$fl = isset($num[1]) ? $num[1] : FALSE;
	}
// 长度
	$len = strlen($int);
// 中文
	$chinese = array();

// 反转的数字
	$str = strrev($int);
	for ($i = 0; $i < $len; $i += 4) {
		$s = array(0 => $str[$i], 1 => $str[$i + 1], 2 => $str[$i + 2], 3 => $str[$i + 3]);
		$j = '';
// 千位
		if ($s[3] !== '') {
			$s[3] = (int) $s[3];
			if ($s[3] !== 0) {
				$j .= $CNum[0][$s[3]] . $CNum[1][3];
			} else {
				if ($s[2] != 0 || $s[1] != 0 || $s[0] != 0) {
					$j .= $CNum[0][0];
				}
			}
		}
// 百位
		if ($s[2] !== '') {
			$s[2] = (int) $s[2];
			if ($s[2] !== 0) {
				$j .= $CNum[0][$s[2]] . $CNum[1][2];
			} else {
				if ($s[3] != 0 && ($s[1] != 0 || $s[0] != 0)) {
					$j .= $CNum[0][0];
				}
			}
		}
// 十位
		if ($s[1] !== '') {
			$s[1] = (int) $s[1];
			if ($s[1] !== 0) {
				$j .= $CNum[0][$s[1]] . $CNum[1][1];
			} else {
				if ($s[0] != 0 && $s[2] != 0) {
					$j .= $CNum[0][$s[1]];
				}
			}
		}
// 个位
		if ($s[0] !== '') {
			$s[0] = (int) $s[0];
			if ($s[0] !== 0) {
				$j .= $CNum[0][$s[0]] . $CNum[1][0];
			} else {
// $j .= $CNum[0][0];
			}
		}
		$j .= $CNum[2][$i / 4];
		array_unshift($chinese, $j);
	}
	$chs = implode('', $chinese);
	if ($fl) {
		$chs .= '点';
		for ($i = 0, $j = strlen($fl); $i < $j; $i++) {
			$t = (int) $fl[$i];
			$chs .= $str[0][$t];
		}
	}
	/***10到20之间**/
	if ($num > 9 && $num < 20) {
		$chs = ltrim($chs, "一");
	}
	return $chs;
}

function checkstr($str, $needle) {

	$tmparray = explode($needle, $str);
	if (count($tmparray) > 1) {
		return true;
	} else {
		return false;
	}
}

/*******找到数字**/
function findNum($str = '') {
	$str = trim($str);
	if (empty($str)) {
		return '';
	}
	$result = '';
	for ($i = strlen($str) - 1; $i > -1; $i--) {
		if (is_numeric($str[$i])) {
			$result .= $str[$i];
		} else {
			break;
		}
	}
	$result = trim($result);
	if (empty($result)) {
		return '';
	}
	for ($i = strlen($result) - 1; $i > -1; $i--) {
		$str2 .= $result[$i];
	}
	return $str2;
}

/*****用户头像***/
function headImg($user_id) {
	$data = BoxModel("system_member")->load($user_id);
	return IMG($data['headimg'], 100, 100);
}

/******替换表情**/
function relpace_emotion($content) {
	$data = S('emotion_data');
	$content = str_replace($data['replace_data']['code'], $data['replace_data']['smilies'], $content);
	return $content;
}

/*****图片路径 water 相对于根目录：image/oyys/icon01.jpg***/
function IMG($imgUrl, $width, $height, $type = 2, $water = "", $position = "rb") {
	$imgUrl = str_replace(ImgDomain, "", $imgUrl);
	$df_img = "/Public/Images/defaultImg.jpg"; //默认图片
	$tmp_name = md5($imgUrl . $water); //缓存略微名
	$save_path = "cache_img/" . $tmp_name . "/" . $width . "_" . $height; //临时图片保存路
	$arr = explode("/", $imgUrl);
	$name = $arr[count($arr) - 1]; //图片名
	$arr_name = explode(".", $name);
	$ext = $arr_name[count($arr_name) - 1];
	$tmp_name .= "." . $ext; //图片后缀
	$tmp_url = $save_path . "/" . $tmp_name; //临时图片网址
	$tmp_name_url = UploadPath . $save_path . "/" . $tmp_name; //临时图片绝对路
	if (!$imgUrl) {
		return $df_img;
	}
	/*****生成过图片**/
	if (file_exists($tmp_name_url)) {
		//dump($tmp_url);
		return ImgDomain . $tmp_url;
	}
	/******是否站外图片***/
	if (strpos($imgUrl, "http://") !== false || strpos($imgUrl, "https://") !== false || strpos($imgUrl, "ftp://") !== false) {
		return $imgUrl;
	} else {
		$pic_dir = UploadPath . $imgUrl;
		if (!is_file($pic_dir)) {
			return $df_img;
		}
	}
	mk_dir(UploadPath . $save_path); //生成临时图片保存路
	$Img = new \Common\Org\Image();
	if ($width && $height) {
		if ($type == 1) {
			@$r = $Img->thumb2($pic_dir, $tmp_name_url, $ext, $width, $height); //居中截取
		} else {
			$r = $Img->thumb($pic_dir, $tmp_name_url, $ext, $width, $height); //等比缩
		}
		//$Img->water_mark($tmp_name_url, $water, $position, $quality = 100, $pct = 100) ; //加水印
		$water = UploadPath . "/" . $water;
		if (is_file($water)) {
			$Img->imageWaterMark($tmp_name_url, 9, $water);
		}
		//$Img->water($tmp_name_url, $water, $tmp_name_url, $alpha=100);
	}
	return ImgDomain . $tmp_url;
}

/******读取配置***/
function config($app, $name) {
	if (!$app) {
		return C();
	}

	if ($app) {
		$data = include APP_PATH . $app . "/Conf/config.php";
		if ($name) {
			return $data[$name];
		} else {
			return $data;
		}
	}
}

/*********get ID 为不用自动增长***/
function get_id($type, $lng = 20) {
	$def = 1000;
	$model = BoxModel("system_gennum");
	$r = $model->where("type='$type'")->find();
	if ($r) {
		$value = intval($r['value']) + 1;
		if ($value < $def) {
			$value = $def;
		}

		$model->where("type='$type'")->save(array('value' => $value));
	} else {
		$value = $def;
		$r = $model->add(array('type' => $type, 'value' => $value));

	}
	return $value;
}

/**对excel里的日期进行格式转化*/
function GetData($val) {
	$jd = gregoriantojd(1, 1, 1970);
	$gregorian = jdtogregorian($jd + intval($val) - 25569);
	return $gregorian;
	/**显示格式为 “月/日/年” */
}

/******下载*****/
function download($filename) {
	if (!is_file($filename)) {
		die('nothing');
	}
	ob_clean();
	$p = explode("/", $filename);
	$name = $p[count($p) - 1];
	//header 的作用是 新建一个被下载的test.xls
	header("Content-Type: application/vnd.ms-excel; charset=utf8");
	header("Content-Disposition: attachment; filename=" . $name);
	//这里是需要被输出的文件
	readfile($filename);
	unlink($filename); //删除文件
}

function deldir($dir) {

	//先删除目录下的文件：

	$dh = opendir($dir);

	while ($file = readdir($dh)) {

		if ($file != "." && $file != "..") {

			$fullpath = $dir . "/" . $file;

			if (!is_dir($fullpath)) {

				unlink($fullpath);

			} else {

				deldir($fullpath);

			}

		}

	}

	closedir($dh);

	//删除当前文件夹：

	if (rmdir($dir)) {

		return true;

	} else {

		return false;

	}

}

/*****加载资源***/
function res_load($url, $type) {
	$GLOBALS['box_res_load'] = array();
	$key = md5($url);
	if ($GLOBALS['box_res_load'][$key]) {
		return;
	}
	$GLOBALS['box_res_load'][$key] = $url;
	if ($type == "js") {
		echo '<script src="' . $url . '"></script>';
	}
	if ($type == "css") {
		echo '<link rel="stylesheet" href="' . $url . '" />';
	}
}

/***********************from表单********************/
function form_select($name, $data, $select, $param = array()) {
	$class = "";

	foreach ($param as $k => $one) {
		$class .= " {$k}='{$one}' ";
	}
	$input = '<select name="' . $name . '" ' . $class . '>';
	$input .= '<option value="" >请选择...</option>';
	foreach ($data as $k => $one) {
		$checked = "";
		if ($k == $select) {
			$checked = 'selected="selected"';
		}
		$input .= ' <option value="' . $k . '" ' . $checked . '>' . $one . '</option>';
	}
	$input .= "</select>";
	return $input;
}

function form_radio($name, $data, $select = "") {
	$input = "";
	$class = "";
	foreach ($param as $k => $one) {
		$class .= $k . "=" . $one;
	}
	foreach ($data as $k => $one) {
		$checked = "";
		if ($k == $select) {
			$checked = 'checked="checked"';
		}
		$input .= '<label><input ' . $class . ' type="radio" ' . $checked . '  value="' . $k . '" name="' . $name . '"/>' . $one . "</label> ";
	}
	return $input;
}

function form_checkbox($name, $data, $select = array()) {
	$input = "";
	$class = "";
	foreach ($param as $k => $one) {
		$class .= $k . "=" . $one;
	}
	foreach ($data as $k => $one) {
		$checked = "";
		if (in_array($k, $select)) {
			$checked = 'checked="checked"';
		}
		$input .= '<label><input ' . $class . ' type="checkbox" ' . $checked . '  value="' . $k . '" name="' . $name . '"/>' . $one . "</label> ";
	}
	return $input;
}

function displayFormHtml($group_name, $values = array(), $view = 0, $display = "horizontal") {
	$param = array(
		'group_name' => $group_name,
		'values' => $values,
		'display' => $display,
		'view' => $view,
	);
	hook("Forms/Index/displayFormHtml", $param);
}

function displayFormGroupHtml($group, $values = array(), $view = 0, $display = "horizontal") {
	$param = array(
		'group' => $group,
		'values' => $values,
		'display' => $display,
		'view' => $view,
	);
	hook("Forms/Index/displayFormGroupHtml", $param);
}

//区块
function Ad($name, $param = array()) {
	$param['name'] = $name;
	hook("Blocks/Index/showHtml", $param);
}

//区块
function AdGroup($name, $param = array()) {
	$param['name'] = $name;
	//dump($param);
	hook("Blocks/Index/showGroupHtml", $param);
}

//上传控件
//	$param=array(
//				'exts'=>$attr['catItem'],//上传的文件类型
//				'inputName'=>$attr["fieldName"],//上传之后数据保存在textarea
//			);
function uploadAddon($param, $fecth = 0) {
	if ($fecth == 1) {
		ob_start();
	}
	// dump($param);
	hook("Upload/Index/showUpload", $param);
	if ($fecth == 1) {
		$content = ob_get_contents();
		ob_end_clean();
		return $content;
	}
}

function downloadXls($filename) {
	if (!is_file($filename)) {
		die('nothing');
	}
	ob_clean();
	$p = explode("/", $filename);
	$name = $p[count($p) - 1];
	//header 的作用是 新建一个被下载的test.xls
	header("Content-Type: application/vnd.ms-excel; charset=utf8");
	header("Content-Disposition: attachment; filename=" . $name);
	//这里是需要被输出的文件
	readfile($filename);
	unlink($filename); //删除文件
}

//html 转换成wx标签
function htmlToWxTags($html) {
	$html = strip_tags($html);
	return $html;
}

?>
